package com.zh.www.utils.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间工具类
 * @author zh
 * @version 1.0
 * @date 2020/6/9 14:56
 * @email 690378361@163.com
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    /**
     * 获取时间格式化字符串
     * @param length
     * @return
     */
    public static String getFormatter(int length) {

        String formatter = "yyyy-MM-dd";
        if (length == 16) {
            formatter = "yyyy-MM-dd HH:mm";
        } else if (length == 19) {
            formatter = "yyyy-MM-dd HH:mm:ss";
        } else if (length == 20) {
            formatter = "yyyy-MM-dd HH:mm:ss.S";
        } else if (length == 21) {
            formatter = "yyyy-MM-dd HH:mm:ss.SS";
        } else if (length == 22) {
            formatter = "yyyy-MM-dd HH:mm:ss.SSS";
        } else if (length == 5){
            formatter = "HH:mm";
        }
        return formatter;
    }

    public static String dateToString(Date time, String format) {
        String timeStr = "";
        //format的格式可以任意
        DateFormat sdf = new SimpleDateFormat(format);
        try {
            timeStr = sdf.format(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeStr;
    }

    /**
     * 时间字符串格式化
     * @param time
     * @param formatter
     * @return
     */
    public static Date stringToDate(String time,String formatter)  {
        DateFormat sdf = new SimpleDateFormat(formatter);
        try {
            return sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /**
     * 时间字符串格式化
     * @param time
     * @return
     */
    public static Date stringToDate(String time) {
        String formatter = getFormatter(time.length());

        Date date = new Date();
        //注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat(formatter);
        try {
            date = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     * 获取当前时间字符串
     * @return
     */
    public static String dateToString(){
        return dateToString(new Date(),getFormatter(19));
    }
}
